package net.fdukedom.epicurus.core.ws;

import java.util.ResourceBundle;

import net.fdukedom.epicurus.domain.entity.User;
import net.fdukedom.epicurus.domain.util.UserHelper;
import net.fdukedom.epicurus.resource.ResourceDispatcher;
import net.fdukedom.epicurus.service.WSMessageHandler;
import net.fdukedom.epicurus.service.interaction.IdentificationRequestReader;
import net.fdukedom.epicurus.service.interaction.ProfileXMLWrapper;
import net.fdukedom.epicurus.service.interaction.ResponseWriter;

/**
 * 
 * @author Alexander Kirakozov
 * 
 */
public class CoreWSMessageHandler extends WSMessageHandler {

	protected String processUpdate(IdentificationRequestReader reader) {
		ResourceBundle bundle = ResourceDispatcher.getInstance().getBundle(
				"bundles.ApplicationResources");
		ResponseWriter response = new ResponseWriter();
		User user = UserHelper.getInstance().findByEmail(reader.getEmail());

		if (user != null && reader.getPassword().equals(user.getPassword())) {
			ProfileXMLWrapper profWrap = new ProfileXMLWrapper(user.getName(),
					user.getSex());

			response.addResult(profWrap.getElement());
			response.setStatus(true);

			return response.toString();
		}

		response.setMessage(bundle.getString("login.errors.failed"));
		response.setStatus(false);

		return response.toString();
	}

	protected String processCommit(IdentificationRequestReader reader) {
		ResourceBundle bundle = ResourceDispatcher.getInstance().getBundle(
				"bundles.ApplicationResources");

		ResponseWriter response = new ResponseWriter();
		User user = UserHelper.getInstance().findByEmail(reader.getEmail());
		System.out.println(reader.getEmail());

		if (user != null && reader.getPassword().equals(user.getPassword())) {
			ProfileXMLWrapper wrap = new ProfileXMLWrapper(reader
					.getParameters().getChild(ProfileXMLWrapper.PROFILE));

			user.setSex(wrap.getSex());
			user.setName(wrap.getNickName());
			UserHelper.getInstance().saveUser(user);

			response.setStatus(true);
			response.setMessage("Profile was updated successfully!");
			return response.toString();
		}

		response.setMessage(bundle.getString("login.errors.failed"));
		response.setStatus(false);

		return response.toString();
	}
}